package com.wangku.springmvc.service;

import com.google.gson.Gson;
import com.wangku.springmvc.utils.redis.RedisPoolUtil;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.Collections;
import java.util.Map;
import java.util.UUID;

/**
 * @description: 微信TOKENservice生成
 * @author: 李赛赛
 * @create: 2018-08-15 15:04
 **/
@Service("wxTokenService")
public class WxTokenService {
    private static final Gson GSON = new Gson();
    private static final String TOKEN_PRE = "wxtoken:";
    private static final String LOGIN_PRE = "wechat_login:";
    Jedis jedis = null;

    public String createToken(Map<String, String> data) {
        if (data == null || data.isEmpty()) {
            return "";
        }
        String token = UUID.randomUUID().toString().replace("-", "");
        try {
            jedis = RedisPoolUtil.getConnect();
            jedis.set(TOKEN_PRE + token, GSON.toJson(data));
            //单客户端登录校验
            jedis.set(LOGIN_PRE+data.get("LoginName"), TOKEN_PRE + token);
            return token;
        } finally {
            if (jedis != null) {
                RedisPoolUtil.closeConnect();
            }
        }
    }
    @SuppressWarnings("unchecked")
    public Map<String, String> getToken(String token) {
        if (token == null || token.isEmpty()) {
            return Collections.emptyMap();
        }
        try {
            jedis = RedisPoolUtil.getConnect();
            String value = jedis.get(TOKEN_PRE + token);
            if (value == null || value.trim().isEmpty()) {
                return Collections.emptyMap();
            }
            return GSON.fromJson(value, Map.class);
        } finally {
            if (jedis != null) {
                RedisPoolUtil.closeConnect();
            }
        }
    }
    public boolean checkToken(String token) {
        if (token == null) {
            return false;
        }

        Jedis jedis = null;
        try {
            jedis = RedisPoolUtil.getConnect();
            return jedis.exists(TOKEN_PRE + token);
        } finally {
            if (jedis != null) {
                RedisPoolUtil.closeConnect();
            }
        }
    }

    public void deleteToken(String token) {
        Jedis jedis = null;
        try {
            jedis = RedisPoolUtil.getConnect();
            jedis.del(TOKEN_PRE + token);
        } finally {
            if (jedis != null) {
                RedisPoolUtil.closeConnect();
            }
        }
    }
}
